import React, { useState, useEffect, useRef } from 'react';
import './InputBox.css';

function InputBox({ inputMessage, setInputMessage, sendMessage, users, currentUser }) {
  const [showMentionList, setShowMentionList] = useState(false);
  const [mentionFilter, setMentionFilter] = useState('');
  const [mentionPosition, setMentionPosition] = useState(0);
  const inputRef = useRef(null);

  const handleInputChange = (e) => {
    const value = e.target.value;
    const lastAtPos = value.lastIndexOf('@');
    
    if (lastAtPos !== -1) {
      const afterAt = value.slice(lastAtPos + 1);
      setMentionFilter(afterAt);
      setMentionPosition(lastAtPos);
      setShowMentionList(true);
    } else {
      setShowMentionList(false);
    }
    
    setInputMessage(value);
  };

  const selectUser = (username) => {
    const beforeAt = inputMessage.slice(0, mentionPosition);
    const afterAt = inputMessage.slice(mentionPosition + mentionFilter.length + 1);
    setInputMessage(`${beforeAt}@${username} ${afterAt}`);
    setShowMentionList(false);
    inputRef.current.focus();
  };

  const filteredUsers = users.filter(user => {
    return user !== currentUser && 
    user.username.toLowerCase().includes(mentionFilter.toLowerCase())
   }
  );

  return (
    <div className="input-container">
      <form className="input-box" onSubmit={sendMessage}>
        <input
          ref={inputRef}
          type="text"
          value={inputMessage}
          onChange={handleInputChange}
          placeholder="输入消息..."
          className="message-input"
        />
        <button type="submit" className="send-button">
          发送
        </button>
      </form>
      {showMentionList && filteredUsers.length > 0 && (
        <div className="mention-list">
          {filteredUsers.map((user) => (
            <div
              key={user}
              className="mention-item"
              onClick={() => selectUser(user)}
            >
              <div className="user-avatar">{user.charAt(0).toUpperCase()}</div>
              <div className="user-name">{user}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default InputBox; 